package com.cheys.webapp.dao;

import java.sql.ResultSet;
import java.sql.SQLException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.stereotype.Repository;

import com.cheys.webapp.model.Admin;
import com.cheys.webapp.model.WebSite;
import com.cheys.webapp.util.StringUtil;

@Repository
public class AdminDao extends AbstractDao {
	@Autowired
	private JdbcTemplate jdbcTemplate;

	public JdbcTemplate getJdbcTemplate() {
		return jdbcTemplate;
	}

	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}
	/**
	 * 根据用户名和密码得到用户信息
	 * @param adminName
	 * @param password
	 * @return admin
	 * */
	public Admin getAdminInfo(String adminName,String password) throws Exception{
		String sql = "select a.id,a.adminName,a.adminPwd from "+Admin.TABLE_NAME+" a where a.adminName='"+adminName+"' and a.adminPwd='"+password+"'";
		final Admin a = new Admin();
		try {
			this.jdbcTemplate.query(sql, new RowCallbackHandler() {
				
				public void processRow(ResultSet rs) throws SQLException {
					// TODO Auto-generated method stub
					a.setId(rs.getInt(1));
					a.setAdminName(rs.getString(2));
					a.setAdminPwd(rs.getString(3));
				}
			});
		} catch (Exception e) {
			throw new Exception("查询异常："+e);
		}
		return a;
	}

	public WebSite selectWebsiteInfo() throws Exception {
		// TODO Auto-generated method stub
		String sql = "select id,title,logo,domain,keyword,owner,phone,telphone,email,address,footer,descript FROM "+WebSite.TABLE_NAME;
		final WebSite a = new WebSite();
		try {
			this.jdbcTemplate.query(sql, new RowCallbackHandler() {
				
				public void processRow(ResultSet rs) throws SQLException {
					// TODO Auto-generated method stub
					a.setId(rs.getInt(1));
					a.setTitle(rs.getString(2));
					a.setLogo(StringUtil.isNotBlank(rs.getString(3)) ? rs.getString(3) : "img/logo.png");
					a.setDomain(rs.getString(4));
					a.setKeyword(rs.getString(5));
					a.setOwner(rs.getString(6));
					a.setPhone(rs.getString(7));
					a.setTelphone(rs.getString(8));
					a.setEmail(rs.getString(9));
					a.setAddress(rs.getString(10));
					a.setFooter(rs.getString(11));
					a.setDescript(rs.getString(12));
				}
			});
		} catch (Exception e) {
			throw new Exception("查询网站信息异常："+e);
		}
		return a;
	}
}
